var t = require("../../utils/util.js"), e = getApp(), a = require("../../utils/pingpp.js"), n = null, o = null;

Page({
    data: {
        orderId: null,
        storeId: e.globalData.storeId || "",
        store: e.globalData.store || "",
        isIpx: e.globalData.isIpx,
        inventories: [],
        confirmModal: !1
    },
    onLoad: function(t) {
        var a = this;
        console.info("onload", t), wx.showLoading({
            title: "查询可用档期"
        });
        var n = new Date(), o = n.getFullYear(), i = n.getMonth() + 1, r = n.getFullYear(), s = n.getMonth() + 1, c = n.getDate(), u = [ "日", "一", "二", "三", "四", "五", "六" ];
        this.setData({
            orderId: this.options.order_id,
            storeId: this.options.store_id,
            cur_year: r,
            cur_month: s,
            cur_day: c,
            today: this.formatDate(r, s, c),
            now_year: o,
            now_month: i,
            weeks_ch: u,
            cur_weekday: null,
            cur_date: null,
            cur_inventories: [],
            cur_inventory: null,
            cur_inventory_label: ""
        }), e.globalData.storeId = t.store_id, this.initOrder(t.order_id, function() {
            a.initRescheduleLogs(t.order_id).then(function(e) {
                console.info("reschedule_logs", e), a.setData({
                    rescheduleLogs: e
                }), a.initStoreSchedule(t.store_id, function() {
                    a.calculateEmptyGrids(r, s), a.calculateDays(r, s);
                });
            });
        });
    },
    onReady: function() {},
    onShow: function() {},
    onHide: function() {},
    onUnload: function() {},
    onPullDownRefresh: function() {},
    onReachBottom: function() {},
    onShareAppMessage: function() {},
    initRescheduleLogs: function(t) {
        return e.getRequest(e.globalData.BASE_URL + "/orders/" + t + "/reschedule_logs");
    },
    initStoreSchedule: function(a, n) {
        var o = this, i = this.data.today.replace(/\-/g, "");
        e.getRequest(e.globalData.BASE_URL + "/stores/" + a + "/calendar?from=" + i + "&to=20191231", {}).then(function(e) {
            var a = [];
            e.forEach(function(e) {
                t.isWeekend(e.date) || (e.inventories.forEach(function(e) {
                    e.sku_title = t.skuLabel(e.sku);
                }), a.push(e));
            });
            var i = (a = a.sort(function(t, e) {
                return +new Date(t.date) - +new Date(e.date);
            }))[a.length - 1].date, r = i.split("-")[0], s = i.split("-")[1], c = i.split("-")[2];
            o.setData({
                inventories: a,
                the_last_date: i,
                the_last_year: r,
                the_last_month: s,
                the_last_day: c
            }), n && n();
        });
    },
    initOrder: function(a, n) {
        var o = this;
        e.getRequest(e.globalData.BASE_URL + "/orders/" + a, {}).then(function(e) {
            e.inventory_label = t.formatInventoryLabel(e.inventory);
            var a = !1;
            e.order_items.forEach(function(t) {
                "weekend" === t.item.inventory_restrictions && (a = !0);
            }), o.setData({
                isWeekendRestriction: a,
                order: e
            }), n && n();
        });
    },
    getInventoriesByDate: function(t) {
        var e = this, a = this.data.inventories.find(function(e) {
            return e.date === t;
        });
        return a ? (a.inventories = a.inventories.filter(function(t) {
            return t.id !== e.data.order.ticket.inventory._id;
        }), a.inventories) : [];
    },
    getWeekdayStrByDate: function(t) {
        return console.info(t, new Date(t).getDay(), this.data.weeks_ch), this.data.weeks_ch[new Date(t).getDay()];
    },
    chooseInventory: function(t) {
        var a = t.detail.value, n = void 0, o = this.data.cur_date && this.getWeekdayStrByDate(this.data.cur_date);
        this.data.inventories.forEach(function(t) {
            t.inventories.forEach(function(t) {
                t.id === a && (n = t);
            });
        }), console.info("inventoryId", a), console.info("inventory", n), console.info("weekday", o), 
        this.setData({
            cur_inventory: n,
            cur_weekday: o,
            cur_inventory_label: this.data.cur_year + "年" + this.data.cur_month + "月" + this.data.cur_day + "日(周" + o + ") " + n.sku_title
        }), e.globalData.cart.inventory = n;
    },
    checkDateValid: function(t) {
        console.log("choosedDate", t);
        var e = !1;
        return this.data.inventories.forEach(function(a) {
            a.date == t && (e = !0);
        }), e;
    },
    getThisMonthDays: function(t, e) {
        return new Date(t, e, 0).getDate();
    },
    getFirstDayOfWeek: function(t, e) {
        return new Date(Date.UTC(t, e - 1, 1)).getDay();
    },
    calculateEmptyGrids: function(t, e) {
        var a = this.getFirstDayOfWeek(t, e), n = [];
        if (a > 0) {
            for (var o = 0; o < a; o++) n.push(o);
            this.setData({
                hasEmptyGrid: !0,
                empytGrids: n
            });
        } else this.setData({
            hasEmptyGrid: !1,
            empytGrids: []
        });
    },
    calculateDays: function(t, e) {
        for (var a = [], n = this.getThisMonthDays(t, e), o = new Date().getDate(), i = 1; i <= n; i++) {
            var r = this.formatDate(t, e, i);
            a.push({
                day: i,
                choosed: i == o,
                date: r,
                inventories: this.getInventoriesByDate(r)
            });
        }
        this.setData({
            days: a
        }), wx.hideLoading();
    },
    handleCalendar: function(t) {
        var e = t.currentTarget.dataset.handle, a = this.data.cur_year, n = this.data.cur_month;
        if ("prev" === e) {
            var o = n - 1, i = a;
            o < 1 && (i = a - 1, o = 12), this.calculateDays(i, o), this.calculateEmptyGrids(i, o), 
            this.setData({
                cur_year: i,
                cur_month: o
            });
        } else {
            var r = n + 1, s = a;
            r > 12 && (s = a + 1, r = 1), this.calculateDays(s, r), this.calculateEmptyGrids(s, r), 
            this.setData({
                cur_year: s,
                cur_month: r
            });
        }
    },
    formatDate: function(t, e, a) {
        return t + "-" + (e > 9 ? e : "0" + (e - 0)) + "-" + (a > 9 ? a : "0" + (a - 0));
    },
    chooseDate: function(t) {
        var e = t.currentTarget.dataset.idx, a = this.data.days, n = this.formatDate(this.data.cur_year, this.data.cur_month, a[e].day);
        this.checkDateValid(n) && (a.forEach(function(t) {
            t.choosed = !1;
        }), this.data.selected = a[e].date, this.setData({
            days: a,
            cur_date: this.data.selected,
            cur_day: a[e].day,
            cur_inventories: a[e].inventories,
            cur_inventory: null,
            cur_inventory_label: null
        }));
    },
    chooseYearAndMonth: function() {
        var t = this.data.cur_year, e = this.data.cur_month;
        n = this.data.cur_year, o = this.data.cur_month;
        for (var a = [], i = [], r = 1900; r <= 2100; r++) a.push(r);
        for (var s = 1; s <= 12; s++) i.push(s);
        var c = a.indexOf(t), u = i.indexOf(e);
        this.setData({
            picker_value: [ c, u ],
            picker_year: a,
            picker_month: i,
            showPicker: !0
        });
    },
    pickerChange: function(t) {
        var e = t.detail.value;
        n = this.data.picker_year[e[0]], o = this.data.picker_month[e[1]];
    },
    tapPickerBtn: function(t) {
        var a = {
            showPicker: !1
        };
        "confirm" === t.currentTarget.dataset.type && (a.cur_year = n, a.cur_month = o, 
        this.calculateEmptyGrids(n, o), this.calculateDays(n, o)), this.setData(a), console.log("app.globalData.cart", e.globalData.cart);
    },
    calcRescheduleFee: function(t) {
        var e = 0;
        return t.order_items.forEach(function(t) {
            e += t.item.advance_price;
        }), console.log("calcRescheduleFee", t.order_items), parseInt(e / 2);
    },
    closeModal: function() {},
    doReschedule: function(t, a, n) {
        e.postRequest(e.globalData.BASE_URL + "/tickets/" + t + "/reschedule", {
            inventory_id: a,
            inventory_version: n
        }).then(function(t) {
            console.info("reschedule", t), wx.showToast({
                title: "改期成功",
                icon: "success",
                duration: 2e3,
                complete: function() {
                    wx.reLaunch({
                        url: "/pages/orders/orders"
                    });
                }
            });
        }, function(t) {
            wx.showModal({
                title: "出错了",
                content: "" + t.message,
                showCancel: !1,
                confirmText: "好的",
                confirmColor: "#259B24",
                success: function(t) {}
            });
        });
    },
    openModal: function() {
        var t = this, n = this.data.cur_inventory_label, o = this.data.cur_inventory.id, i = this.data.cur_inventory.version, r = (this.data.store.name, 
        this.data.orderId), s = this.data.order.ticket._id, c = 0 === this.data.rescheduleLogs.length, u = this.calcRescheduleFee(this.data.order);
        console.log("this.data.cur_inventory", this.data.cur_inventory), console.log("reschedule_charge_amount", u), 
        wx.showModal({
            title: "确认更改档期",
            content: "" + n,
            showCancel: !0,
            cancelText: "重选",
            cancelColor: "#C2A469",
            confirmText: c ? "确认改期" : "支付",
            confirmColor: "#259B24",
            success: function(n) {
                n.confirm && (c ? (console.info("可免费改期"), t.doReschedule(s, o, i)) : e.postRequest(e.globalData.BASE_URL + "/orders/" + r + "/charge", {
                    action: "reschedule_charge",
                    amount: u,
                    note: "订单改期手续费"
                }).then(function(n) {
                    console.info("charge", n), a.createPayment(n, function(a, c) {
                        console.info("payment", a, c), "success" == a ? t.doReschedule(s, o, i) : (console.log("支付已取消", a + " " + c.msg + " " + c.extra), 
                        wx.showToast({
                            title: "支付已取消",
                            icon: "none",
                            duration: 2e3,
                            success: function() {
                                k;
                            }
                        }), e.postRequest(e.globalData.BASE_URL + "/orders/" + r + "/uncharge", {
                            charge_id: n.id
                        }).then(function(t) {
                            console.info("客户端撤销支付", t);
                        }));
                    });
                }, function(t) {}));
            },
            fail: function(t) {},
            complete: function(t) {}
        });
    },
    confirmHandler: function() {
        wx.navigateTo({
            url: "/pages/order-detail/order-detail",
            success: function(t) {},
            fail: function(t) {},
            complete: function(t) {}
        }), this.setData({
            confirmModal: !1
        });
    }
});